package str;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : Rookie
 * @description : 大数相加
 * @date : 2023/10/18
 */
public class BigNumberAdd {

    public static void main(String[] args) {
        String num1 = "8299216549841626456481515";
        String num2 = "216564952659951313116";
        String result = add(num1,num2);
        System.out.println(result);
    }

    private static String add(String num1,String num2) {
        List<Integer> result = new ArrayList<>();
        // 翻转字符串
        String s1 = reverseStr(num1.toCharArray(), 0, num1.length() - 1);
        String s2 = reverseStr(num2.toCharArray(), 0, num2.length() - 1);
        StringBuilder sb1 = new StringBuilder(s1);
        StringBuilder sb2 = new StringBuilder(s2);
        // 低位补0
        int subLen = sb1.length() - sb2.length();
        if (subLen > 0) {
            for (int i = 0;i<subLen;i++) {
                sb2.append(0);
            }
        }
        if (subLen < 0) {
            for (int i = 0; i < -subLen; i++) {
                sb1.append(0);
            }
        }
        // 两数相加
        // 进位标记
        int pretty = 0;
        for (int i = 0; i < sb1.length(); i++) {
            char c1 = sb1.charAt(i);
            char c2 = sb2.charAt(i);
            int res = Character.getNumericValue(c1) + Character.getNumericValue(c2) + pretty;
            if (res < 10) {
                result.add(res);
                pretty = 0;
            } else {
                result.add(res-10);
                pretty = 1;
            }
        }
        Collections.reverse(result);
        return result.stream()
                .map(String::valueOf)
                .collect(Collectors.joining());
    }

    private static String reverseStr(char[] chars,int start,int end) {
        if (start < end) {
            swap(chars,start,end);
            start++;
            end--;
            return reverseStr(chars,start,end);
        }
        return new String(chars);
    }

    private static void swap(char[] chars,int i,int j) {
        char temp = chars[i];
        chars[i] = chars[j];
        chars[j] = temp;
    }
}
